import axios from 'axios'
import router from "../router/index.js";
import {Modal,Notify} from '@opentiny/vue'
import {tokenName, userName} from "../config";
import {start, close} from "./nprogress.js";

const request = axios.create({
    // baseURL: '/api',
    // baseURL: '',
    timeout: 100000
})

// request 拦截器
request.interceptors.request.use(config => {
    start()
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    const token = localStorage.getItem(tokenName) ? localStorage.getItem(tokenName) : '';
    if (token) {
        config.headers[tokenName] = token;  // 设置请求头
    }
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        if (res.code === 40003){
            // 未登录
            // 清除缓存
            localStorage.removeItem(userName)
            localStorage.removeItem(tokenName)
            // 提示信息
            Notify({
                type: 'warning',
                message: res.message,
                position: 'top-right',
                duration: 2000
            })
            // 返回登录页
            router.push('/login')
        }

        if (res.code === 0) {
            console.log(res)
            Modal.message({message:res.message,status:'error'})
            // Router.push("/login")
        }
        close()
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default request
